package org.ofbiz.consolidation.util;

import java.util.LinkedList;
import java.util.List;

import org.ofbiz.entity.GenericValue;

public class Classify {
	
	public static void main(String [] argv) {
	}
	
	public List<CombineableOrder> classfy(List<GenericValue> orderList) {
		return this.classfy(orderList, null);
	}
	
	public List<CombineableOrder> classfy(List<GenericValue> orderList, Double similarityFactor) {
		List<CombineableOrder> combineableOrderList = new LinkedList<CombineableOrder>(); 
		
		List<GenericValue> copyList = new LinkedList<GenericValue>();
		for(GenericValue order : orderList) {
			copyList.add(order);
		}
		
		Similarity similarity = new Similarity();
		
		if(similarityFactor == null) {
			similarityFactor = 0.6d;
		}
		
		for(GenericValue curOrder : orderList) {
			if(!copyList.contains(curOrder)) {
				continue;
			}
			
			// save combineable orders
			List<GenericValue> list = new LinkedList<GenericValue>();
			list.add(curOrder);
			
			String curPartyId = curOrder.getString("partyId");
			String curCountryGeoId = curOrder.getString("countryGeoId");
			//String curStateProvinceGeoId = curOrder.getString("stateProvinceGeoId");
			String curCity = curOrder.getString("city");
			String curAddress1 = curOrder.getString("address1");
			String curAddress2 = curOrder.getString("address2");
			
			copyList.remove(curOrder);
			
			for(GenericValue order : copyList) {
				// continue when the customers are not same
				if(!curPartyId.equals(order.getString("partyId"))) {
					continue;
				}
				
				String countryGeoId = order.getString("countryGeoId");
				//String stateProvinceGeoId = order.getString("stateProvinceGeoId");
				String city = order.getString("city");
				String address1 = order.getString("address1");
				String address2 = order.getString("address2");
				
				if(!curCountryGeoId.equals(countryGeoId)
					|| !curCity.equals(city)) {
					continue;
				}
				
				// check the address TODO change the factor
				if(similarity.sim(address1 + address2, curAddress1 + curAddress2) < similarityFactor) {
					continue;
				}
				
				list.add(order);
			}
			
			if(list.size() > 1) {
//				List<GenericValue> resultList = new LinkedList<GenericValue>();
//				for(GenericValue order : list) {
//					copyList.remove(order);
//					try {
//						resultList.add(order.getDelegator().findByPrimaryKey("OrderHeader", UtilMisc.toMap("orderId", order.getString("orderId"))));
//					} catch (GenericEntityException e) {
//						e.printStackTrace();
//					}
//				}
				CombineableOrder co = new CombineableOrder();
				co.setKey(curPartyId);
				co.setOrderList(list);
				combineableOrderList.add(co);
			}
		}
		
		return combineableOrderList;
	}

}
